<?php


namespace app\admin\controller\goods;

use app\admin\service\goods\GoodsCateService;
use app\common\controller\BaseAdmin;
use app\common\model\GoodsCate as GoodsCateModel;
use think\facade\Config;

class GoodsCate extends BaseAdmin
{


    public function index(){
        if ($this->request->isAjax()){
            //获取搜索条件
            $data =$this->request->except(['page'],'get');

            $model = new GoodsCateModel();
            $list = $model->withSearch($this->searchFields($data),$this->searchData($data))
                ->order('id','desc')
                ->paginate($data['limit'], false);
            $data =  $this->getTreeOrder($list->getCollection());
            return $this->tableJson($data,$list->total());
        }

        //
        return $this->fetch('goods/cate/index');
    }

    /**
     * 新建/编辑模板
     * @return array|string
     */
    public function edit(){
        if ($this->request->isAjax()){
            $data = $this->request->param();
            //编辑或者添加数据
            $scene = empty($data['id'])?'add':'edit';

            return json(GoodsCateService::storeGoodsCate($data,$scene));
        }
        //上级分类
        $parent = GoodsCateModel::where(['state'=>1])->field('id,name,parent_id')->select()->toArray();
//        print_r($parent);exit;
        $parent =  $this->getTreeOrder($parent);
      //  print_r($parent);exit;
        $this->assign('cate', $parent);
        $id = $this->request->get('id');
        if ($id){
            $list = GoodsCateModel::where('id', $id)->find();

            $this->assign('list', $list);
        }

        return $this->fetch('goods/cate/edit');
    }
    /**
     * 状态更改
     */
    public function change(){
        $id = $this->request->param('id');
        $model = GoodsCateModel::find($id);
        $model->state = $this->request->param('state');
        if ($model->save()){
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 删除批量删除
     */
    public function remove(){
        if ($this->request->isAjax()){
            $ids = $this->request->param('ids');

            GoodsCateModel::destroy($ids);

            //连带删除
            if (!is_array($ids)){
                $uid[] = $ids;
            }else{
                $uid = $ids;
            }

            GoodsCateModel::where('parent_id','in',$uid)->delete();
            $this->success('删除成功');

        }else{
            $this->error('非法请求');
        }
    }

}